package com.gpjcjl.ui;

import android.annotation.SuppressLint;
import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.base.lib.JsonUtil;
import com.base.lib.Logs;
import com.base.lib.SharedHelper;
import com.gpjcjl.App;
import com.gpjcjl.Config;
import com.gpjcjl.entity.InitInfo;
import com.gpjcjl.entity.Result;
import com.gpjcjl.http.HttpManager;
import com.gpjcjl.http.HttpService;
import com.gpjcjl.http.RxSchedulers;
import com.gpjcjl.http.SingleLiveEvent;

import io.reactivex.disposables.CompositeDisposable;

/**
 * @author yinbiao
 */
public class MainViewModel extends AndroidViewModel {

    private static final String TAG = "MainViewModel";

    CompositeDisposable disposable;

    public MainViewModel(@NonNull Application application) {
        super(application);
        disposable = new CompositeDisposable();
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        //页面销毁时调用
        Logs.d(TAG, "onCleared:");
        disposable.clear();
    }

    /**
     * 获取初始化配置
     *
     * @return LiveData
     */
    @SuppressLint("HardwareIds")
    public LiveData<Result<InitInfo>> init() {
        MutableLiveData<Result<InitInfo>> result = new SingleLiveEvent<>();
        disposable.add(HttpManager.getInstance().getService(HttpService.class)
                .init(App.getInstance().getAndroidId())
                .compose(RxSchedulers.ioMain())
                .subscribe(bean -> {
                    //缓存配置信息
                    String produce = JsonUtil.toJson(bean.getData().getProduce());
                    String property = JsonUtil.toJson(bean.getData().getProperty());
                    SharedHelper.getInstance().put(Config.CACHE_PRODUCE, produce);
                    SharedHelper.getInstance().put(Config.CACHE_PROPERTY, property);
                    result.setValue(bean);
                }, throwable -> {
                    result.setValue(Result.error(throwable.getMessage()));
                    Logs.e(TAG, throwable.toString() + "-----" + throwable.getMessage());
                }));
        return result;
    }


}
